package cn.btks.backstagemanage.app.service.impl;

import cn.btks.backstagemanage.app.pojo.AppVersion;
import cn.btks.backstagemanage.app.repository.AppVersionRepository;
import cn.btks.backstagemanage.app.service.AppVersionService;
import cn.btks.commonserver.result.Constants;
import cn.btks.commonserver.result.ResultState;
import cn.btks.commonserver.result.StateInfo;
import cn.btks.commonserver.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

/**
 * @Author lijun
 * @Date 2021/4/9 15:23
 */
@Service
public class AppVersionServiceImpl implements AppVersionService {

    @Autowired
    AppVersionRepository appVersionRepository;

    @Override
    public List<AppVersion> findAll() {
        return appVersionRepository.findAll();
    }

    @Override
    public ResultState save(AppVersion appVersion, MultipartFile multipartFile, HttpServletRequest request) {
        if(!multipartFile.isEmpty()){
            String appFileName = multipartFile.getOriginalFilename();
            String pathname = request.getSession(true).getServletContext().getRealPath("//") + "app/" + appFileName;
            System.out.println(pathname);
            if (FileUtil.fileUpload(multipartFile, pathname)) {
                return new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg(), "文件上传失败");
            }
            appVersion.setFilePath("app/" + appFileName);
        }
        AppVersion appVersion1 = appVersionRepository.save(appVersion);
        return appVersion1 != null ? new ResultState(StateInfo.SAVE_OK.getCode(), StateInfo.SAVE_OK.getMsg(),appVersion1) :
                new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg());
    }

    @Override
    public ResultState update(AppVersion appVersion) {
        if(appVersion.getId() != null){
            Optional<AppVersion> optional = appVersionRepository.findById(appVersion.getId());
            if(optional.isPresent()){
                AppVersion appVersion1 = appVersionRepository.save(appVersion);
                return appVersion1 != null ? new ResultState(StateInfo.SAVE_OK.getCode(), StateInfo.SAVE_OK.getMsg(),appVersion1) :
                        new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg());
            }
        }
        return new ResultState(StateInfo.SAVE_ERROR1.getCode(), StateInfo.SAVE_ERROR1.getMsg());
    }
}
